import { userInfoSubmit } from '../../../api/user'

const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    items: ['name', 'department'],
    user: {
      name: '',
      department: '',
      nameRules: [
        {
          required: true,
          message: '请输入姓名',
          trigger: 'blur'
        },
        {
          pattern: '^[\u4E00-\u9FA5]{2,10}$',
          message: '姓名必须是2到10个中文',
          trigger: 'blur'
        }
      ],
      departmentRules: {
        required: true,
        message: '请输入科室',
        trigger: 'blur'
      }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.items) {
      this.setData({
        items: options.items.split(',')
      })
    }
    wx.lin.initValidateForm(this)
    this.setData({
      ['user.name']: app.globalData.userInfo.name,
      ['user.department']: app.globalData.userInfo.department
    })
  },

  submit: function (event) {
    const { detail } = event
    if (detail.isValidate) {
      userInfoSubmit({
        name: detail.values.name || this.data.user.name,
        department: detail.values.department || this.data.user.department
      }).then((res) => {
        if (res.code == 200) {
          app.setUserInfo({
            name: res.data.name,
            department: res.data.department,
            phone: res.data.phone
          })
          wx.navigateBack({
            delta: 1,
            success: function () {
              wx.showToast({
                title: '提交成功'
              })
            }
          })
        }
      })
    }
  }
})
